# @FileName  : msql.py
# @Time      : 2021/10/6 0014  9:15
# @Author    : LuZhaoHui
# @Software  : PyCharm

from queue import Queue

from pymysql import *
import threading
from tool import *

MAX_MYSQLQUEUENUMS = 9


class mysqlProc():
    def __init__(self, host, port, user, password, db):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.db = db
        self.op = 0
        self.ver = 0
        self.conn = None
        self.cur = None
        self.err = None
        self.ret = 0
        self.status = False
        self.queue = Queue(MAX_MYSQLQUEUENUMS)
        self.errDict = {}
        self.classDict = {}
        self.conditionDict = {}
        self.lockDict = {}
        self.checkDict = {}
        self.getErr()
        self.getClass()
        self.getCondition()
        self.getLock()
        self.getCheck()

    def __del__(self):
        print("mysql thread stop")
        # stop_thread(self._thread)

    def setSys(self, op, ver):
        self.op = op
        self.ver = ver

    def exit(self):
        self.close()
        self.__del__()

    def close(self):
        if self.cur != None:
            self.cur.close()
            self.cur = None
        if self.conn != None:
            self.conn.close()
            self.conn = None

    def open(self):
        self.err = None
        try:
            if self.conn == None:
                self.err = ''
                if len(self.host) > 0 and self.port > 0 and len(self.user) > 0:
                    self.conn = connect(host=self.host,
                                        port=self.port,
                                        user=self.user,
                                        passwd=self.password,
                                        db=self.db)
            if self.conn != None and self.cur == None:
                self.cur = self.conn.cursor()
        except Exception as e:
            self.err = e
            self.conn = None
            self.close()
            saveLog(curFunc(e), log='error')
        self.status = self.conn != None
        return self.status

    # def getQueue(self):
    #     while True:
    #         if not self.queue.empty():
    #             sqls = self.queue.get()
    #             # print(sqls)
    #             self.getExec(sqls)
    #         time.sleep(1)

    # def putQueue(self, sqls):
    #     try:
    #         self.queue.put(sqls)
    #     except Exception as e:
    #         saveLog(curFunc(e), log='error')
    #     return self.queue.qsize()

    def getExec(self, sqls, all=False):
        self.err = None
        self.ret = 0
        saveLog(sqls)
        try:
            if self.open():
                self.ret = self.cur.execute(sqls)
                self.conn.commit()
        except Exception as e:
            self.close()
            self.err = e
            saveLog(curFunc(e), log='error')
        if self.ret > 0:
            if all:
                data = self.cur.fetchall()
            else:
                data = self.cur.fetchone()
            return data
        return None

    def errStr(self, errCode):
        return self.errDict.get(errCode, '[%d]未知错误' % (errCode))

    def getErr(self):
        # 获取错误码
        sqls = "call getPara(90,90)"
        data = self.getExec(sqls, True)
        self.errDict.clear()
        if data == None:
            return
        for e in data:
            if len(e):
                self.errDict[e[0]] = e[2]

    def classStr(self, classCode):
        return self.classDict.get(classCode, 'XX')

    def getClass(self):
        # 获取类别
        sqls = "call getPara(40,40)"
        data = self.getExec(sqls, True)
        self.classDict.clear()
        if data == None:
            return
        for e in data:
            if len(e):
                self.classDict[e[0]] = e[2]

    def conditionStr(self, conditionCode):
        return self.conditionDict[conditionCode]

    def getCondition(self):
        # 获取条件
        sqls = "call getPara(51,56)"
        data = self.getExec(sqls, True)
        self.conditionDict.clear()
        if data == None:
            return
        for e in data:
            if len(e):
                self.conditionDict[e[1]] = e[2]

    def lockStr(self, lockCode):
        return self.lockDict[lockCode]

    def getLock(self):
        # 获取分配状态
        sqls = "call getPara(58,58)"
        data = self.getExec(sqls, True)
        self.lockDict.clear()
        if data == None:
            return
        for e in data:
            if len(e):
                self.lockDict[e[1]] = e[2]

    def checkStr(self, checkCode):
        return self.checkDict[checkCode]

    def getCheck(self):
        # 获取核查状态
        sqls = "call getPara(59,59)"
        data = self.getExec(sqls, True)
        self.checkDict.clear()
        if data == None:
            return
        for e in data:
            if len(e):
                self.checkDict[e[1]] = e[2]

    def addActLog(self, act, actInfo):
        # 行为日志记录-addActLog
        sqls = "call addActLog(%d,%d,\'%s\',%d,\'%s\') " % \
               (act, nowDateTimeInt(), actInfo, self.op, self.ver)
        return self.getExec(sqls)

    def loginOp(self, op, password, uuid):
        # 登录认证
        sqls = "call checkOp(%d,\'%s\',\'%s\')" % (op, password, uuid)
        # sqls = "call getOps()"
        return self.getExec(sqls, all=True)

    def setOpPass(self, op, password):
        # 登录认证
        sqls = "call setOpPass(%d,\'%s\')" % (op, password)
        return self.getExec(sqls)

    def checkDir(self, dirName, conditionStr, checkResult, state):
        # 核查目录结果
        sqls = "call checkDir(%d,\'%s\',\'%s\',\'%s\',%d)" % (self.op,
                                                              dirName,
                                                              conditionStr,
                                                              checkResult,
                                                              state)
        return self.getExec(sqls)

    def getDir(self, dirName):
        # 获取目录信息
        sqls = "call getDir(%d,\'%s\')" % (self.op, dirName)
        return self.getExec(sqls, all=True)

    def setDir(self, dirName):
        # 分配目录信息
        sqls = "call setDir(%d,\'%s\')" % (self.op, dirName)
        return self.getExec(sqls, all=True)

    def modDir(self, dirName, dirNums):
        # 刷新目录信息
        sqls = "call modDir(%d,\'%s\',%d)" % (self.op, dirName, dirNums)
        return self.getExec(sqls)

    def addFile(self, dirName, fileName, fileFullName, fileSN, fileAB, fileWidth, fileHeight, fileColor, fileMd5,
                fileByte):
        # 上传文件
        sqls = "call addFile(%d,\'%s\',\'%s\',\'%s\',%d,\'%s\',%d,%d,%d,\'%s\',%d)" % (self.op,
                                                                                       dirName,
                                                                                       fileName,
                                                                                       fileFullName,
                                                                                       fileSN,
                                                                                       fileAB,
                                                                                       fileWidth,
                                                                                       fileHeight,
                                                                                       fileColor,
                                                                                       fileMd5,
                                                                                       fileByte)
        return self.getExec(sqls)

    def getDirs(self):
        # 获取可分配目录信息
        sqls = "call getDirs(%d)" % (self.op)
        return self.getExec(sqls, all=True)

    def getPara(self, type):
        # 查询打印服务器数据-getPrints()
        sqls = "call getPara(%d)" % (type)
        return self.getExec(sqls, all=True)


def procLogQueue(self):
    pass


class MysqlProc(threading.Thread):
    def __init__(self, msql, ):
        super().__init__()
        self.mysql = msql

    def run(self):
        self.mysql.open()
